'use strict'

const fs=require("fs");
const router=require("koa-router")();

//获取文件

function getRouterFlies(temPath) {
    let dir=__dirname || temPath;
    

    let Flies=fs.readdirSync(dir);

    let rFlies=Flies.filter(item=>{
        return item.endsWith(".js") && item != "index.js"
    })
    return rFlies
}


//注册文件

function registerRouter(router,rFlies) {
    
    rFlies.forEach(item => {
        let temPath=__dirname+ '/'+item;
        let obj=require(temPath);
        

        for (const key in obj) {

            let rMeth=key.split(" ")[0];
            let rPath=key.split(" ")[1];
            let rFunction =obj[key]


            if (rMeth=="get") {
                router.get(rPath,rFunction)
                
            } else if(rMeth=="post"){
                router.post(rPath,rFunction)
                
            }else if(rMeth=="put"){
                router.put(rPath,rFunction)
                
            }else if(rMeth=="delete"){
                router.delete(rPath,rFunction)
                
            }else{
                console.log("请求方法不正确");
            }
        }
        console.log(obj);
    });
return router.routes()
    
}

module.exports=function () {
    let rFlies=getRouterFlies();
    console.log(rFlies);
    
    let fn =registerRouter(router,rFlies)
    return fn
}